#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import requests
from sqlalchemy.sql.expression import func

from trest.utils import utime
from trest.logger import SysLogger
from trest.config import settings
from trest.exception import JsonError

from applications.common.models.user_binding import UserBinding


class WxampSercice(object):
    @staticmethod
    def save_userinfo(oppid, openid, info, user_id = 0):
        """插入、更新第三方用户信息
        """
        param = {
            'oppid': oppid,
            'openid': openid,
            'info': info,
            'user_id': user_id,
        }
        try:
            count = UserBinding.session \
                .query(func.count(UserBinding.id)) \
                .filter(UserBinding.type == 1) \
                .filter(UserBinding.openid == openid) \
                .filter(UserBinding.oppid == oppid) \
                .scalar()
            if count == 0:
                param['type'] = 1
                param['updated_at'] = 0
                param['created_at'] = utime.timestamp(3)
                obj = UserBinding(**param)
                UserBinding.session.add(obj)
                UserBinding.session.commit()
            else:
                param['updated_at'] = utime.timestamp(3)
                UserBinding.Update \
                    .filter(UserBinding.type == 1) \
                    .filter(UserBinding.openid == openid) \
                    .filter(UserBinding.oppid == oppid) \
                    .update(param)
                UserBinding.session.commit()
        except Exception as e:
            UserBinding.session.rollback()
            SysLogger.error(e)
            raise JsonError('insert error')
        return param
